package com.cl.blog.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.blog.document.ExcelDto;
import com.cl.blog.entity.*;
import com.cl.blog.exception.WebException;
import com.cl.blog.service.*;
import com.cl.blog.mapper.BContentExamineMapper;
import com.cl.blog.vo.ExamineNoPassVo;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author object
 * @description 针对表【b_content_examine】的数据库操作Service实现
 * @createDate 2024-03-14 17:13:59
 */
@Service
public class BContentExamineServiceImpl extends ServiceImpl<BContentExamineMapper, BContentExamine>
		implements BContentExamineService {

	private static final String filePath = System.getProperty("user.dir");

	@Resource
	BContentService bContentService;
	@Resource
	BContentExamineMapper bContentExamineMapper;
	@Resource
	BUserService bUserService;
	@Resource
	BAdminService bAdminService;
	@Autowired
	BNewNoticeService bNewNoticeService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Object noPass(ExamineNoPassVo examineNoPassVo, Integer adminId) {


		System.out.println("获得的数据----" + examineNoPassVo);
		// 添加管理员的操作记录
		BContentExamine bContentExamine = new BContentExamine();
		bContentExamine.setContentId(examineNoPassVo.getContentId());
		bContentExamine.setContentTypeId(examineNoPassVo.getContentTypeId());
		bContentExamine.setMsg(examineNoPassVo.getMsg());
		bContentExamine.setTime(LocalDateTime.now());
		bContentExamine.setAdminId(adminId);
		bContentExamine.setUserId(examineNoPassVo.getUserId());
		bContentExamine.setStatus(examineNoPassVo.getStatus());

		BContent bContent = bContentService.getById(examineNoPassVo.getContentId());
		String title = bContent.getTitle().replace("#", "");
		boolean b = bContentExamineMapper.saveExamine(bContentExamine);
		BNewNotice bNewNotice = new BNewNotice();
		bNewNotice.setCreateTime(LocalDateTime.now());
		bNewNotice.setStatus(0);
		bNewNotice.setAdminId(adminId);
		bNewNotice.setUserId(examineNoPassVo.getUserId());
		bNewNotice.setType(1);
		bNewNotice.setTitle("通知");
		Integer status = null;
		// 修改文章状态
		if (examineNoPassVo.getId() == 1) {
			// 通过
			status = 2;
			bNewNotice.setContent("你的文章《" + title + "》于" + LocalDateTime.now() + "通过了审核");
		} else if (examineNoPassVo.getId() == 2) {
			// 不通过
			status = 3;
			bNewNotice.setContent("你的文章《" + title + "》于" + LocalDateTime.now() + "未通过审核");
		} else if (examineNoPassVo.getId() == 3) {
			// 重审
			status = 1;
			bNewNotice.setContent("你的文章《" + title + "》于" + LocalDateTime.now() + "进行了重审");
		}
		boolean a = bContentService.update(new UpdateWrapper<BContent>()
				.eq("id", examineNoPassVo.getContentId())
				.set("status", status)
		);
		// 通告
		boolean save = bNewNoticeService.save(bNewNotice);
		if (save && a) {
			return true;
		}
		return false;
	}

	@Override
	public String downLoad() throws IOException {
		List<BContentExamine> list = this.list();
		for (BContentExamine b : list) {
			// 查作者名字以及文章标题
			BUser bUser = bUserService.getById(b.getUserId());
			b.setAuthor(bUser.getNickname() == null ? bUser.getUsername() : bUser.getNickname());

			BContent bContent = bContentService.getById(b.getContentId());
			b.setContentTitle(bContent.getTitle());

			BAdmin bAdmin = bAdminService.getById(b.getAdminId());
			b.setAdmin(bAdmin.getNickname() == null ? bAdmin.getUsername() : bAdmin.getNickname());
		}

		// 数据处理
		List<ExcelDto> excelDtoList = data(list);
		// 进行导出
		String filename = filePath + "/操作日志/" + System.currentTimeMillis() + ".xlsx";
		File file = new File(filename);

		File parentFile = file.getParentFile();

		if (!parentFile.exists()) {
			boolean newFile = parentFile.mkdirs();
			if (!newFile) {
				throw new WebException("抱歉，目录创建失败");
			}
		}

		if (!file.exists()) {
			boolean newFile = file.createNewFile();
			if (!newFile) {
				throw new WebException("文件创建失败");
			}
		}

		System.out.println("需要导出的数据：" + excelDtoList);
		System.out.println("文件路径：" + filename);
		// 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
		// 如果这里想使用03 则 传入excelType参数即可
		EasyExcel.write(filename, ExcelDto.class)
				.sheet("操作日志")
				.doWrite(excelDtoList);

		return filename;
	}


	/**
	 * 对于导出的数据进行处理
	 *
	 * @param list 传入的数据库数据
	 * @return 导出的实体类
	 */
	private List<ExcelDto> data(List<BContentExamine> list) {
		List<ExcelDto> excelDtos = Lists.newArrayList();

		for (BContentExamine b : list) {
			ExcelDto excelDto = new ExcelDto();
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append(b.getAdmin() +
					"(" + b.getAdminId() +
					")对用户" + b.getAuthor()
					+ "的文章进行了审核，审核结果为" +
					b.getStatus());
			;
			if (b.getStatus() == "不通过") {
				stringBuilder.append("，原因为：" + b.getMsg());
			}
			excelDto.setMsg(String.valueOf(stringBuilder));
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");


			excelDto.setTime(b.getTime().format(formatter));

			excelDtos.add(excelDto);
		}
		return excelDtos;
	}
}




